package com.kk.aopdemo.aspect;

import com.kk.aopdemo.pojo.SysLogBO;
import com.kk.aopdemo.service.SysLogService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.SourceLocation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @author MH
 */
@Slf4j
@Aspect
@Component
public class SysLogAspect {

    @Autowired
    private SysLogService sysLogService;

    @Pointcut("@annotation(com.kk.aopdemo.anotation.SysLog)")
    public void sysAspectPointcut() {
    }

    @Around("sysAspectPointcut()")
    public void around(ProceedingJoinPoint point) throws Throwable {
        long beginTime = System.currentTimeMillis();
        log.info("环绕通知 start time : " + new Date(beginTime));

        Signature signature = point.getSignature();
        Object target = point.getTarget();
        Object aThis = point.getThis();
        SourceLocation sourceLocation = point.getSourceLocation();
        String kind = point.getKind();
        JoinPoint.StaticPart staticPart = point.getStaticPart();
        Class<? extends ProceedingJoinPoint> aClass = point.getClass();
        //拿到切点的方法参数
        Object[] args = point.getArgs();
        for (int i = 0; i < args.length; i++) {
            boolean b = args[i] instanceof SysLogBO;
            if (b) {
                ((SysLogBO) args[i]).setParams("wsk" + i);
            }
        }


        Object result = point.proceed();

        long endTime = System.currentTimeMillis();
        log.info("环绕通知 end time : " + new Date(endTime));
        log.info("环绕通知 cost time : " + new Date(endTime - beginTime));
    }

    @Before("sysAspectPointcut()")
    public void before() {
        long beginTime = System.currentTimeMillis();
        log.info("前置通知 start time : " + new Date(beginTime));
    }

    /**
     * 异常通知，如果被try catch捕捉，就不会执行了
     */
    @AfterThrowing("sysAspectPointcut()")
    public void afterThrowing() {
        long beginTime = System.currentTimeMillis();
        log.info("异常通知 start time : " + new Date(beginTime));
    }

    @AfterReturning("sysAspectPointcut()")
    public void afterReturning() {
        long beginTime = System.currentTimeMillis();
        log.info("后置通知 start time : " + new Date(beginTime));
    }

    @After("sysAspectPointcut()")
    public void after() {
        long beginTime = System.currentTimeMillis();
        log.info("最终通知 start time : " + new Date(beginTime));
    }


}
